package com.lingxu.base.system.api.impl;

import com.lingxu.base.common.constant.DataBaseConstant;
import com.lingxu.base.common.exception.BussException;
import com.lingxu.base.common.util.IPUtils;
import com.lingxu.base.common.util.ObjectConvertUtils;
import com.lingxu.base.common.util.SpringContextUtils;
import com.lingxu.base.system.api.ISysBaseAPI;
import com.lingxu.base.system.common.entity.SysLog;
import com.lingxu.base.system.common.mapper.SysLogMapper;
import com.lingxu.base.system.manage.entity.SysUser;
import com.lingxu.base.system.manage.mapper.SysUserMapper;
import com.lingxu.base.system.manage.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Date;


/**
 * @Description: 底层共通业务API，提供其他独立模块调用
 * @Author: scott
 * @Date:2019-4-20 
 * @Version:V1.0
 */
@Slf4j
@Service
public class SysBaseApiImpl implements ISysBaseAPI {
	/** 当前系统数据库类型 */
	public static String DB_TYPE = "";
//	@Autowired
//	private ISysMessageTemplateService sysMessageTemplateService;
	@Resource
	private SysLogMapper sysLogMapper;
	@Resource
	private SysUserMapper userMapper;


	@Override
	public void addLog(String LogContent, Integer logType, Integer operatetype,SysUser sysUser) {
		SysLog sysLog = new SysLog();
		//注解上的描述,操作日志内容
		sysLog.setLogcontent(LogContent);
		sysLog.setLogtype(logType);
		sysLog.setOperatetype(operatetype);
		try {
			//获取request
			HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
			//设置IP地址
			sysLog.setIp(IPUtils.getIpAddr(request));
		} catch (Exception e) {
			sysLog.setIp("127.0.0.1");
		}
		//获取登录用户信息
		if(sysUser != null){
			sysLog.setUserid(sysUser.getId());
			sysLog.setUsername(sysUser.getUsername());
			sysLog.setRealname(sysUser.getName());
			sysLog.setCreateby(sysUser.getId());
		}
		sysLog.setCreatetime(new Date());
		//保存系统日志
		sysLogMapper.insert(sysLog);
	}


	/**
	 * 通过账号名查询用户 单独抽开是为了加缓存，加速校验token的过程
	 * @param username
	 * @return
	 */
	@Override
	public LoginUser getUserByName(String username) {
		if(ObjectConvertUtils.isEmpty(username)) {
			return null;
		}
		LoginUser loginUser = new LoginUser();
		SysUser sysUser = userMapper.getByName(username,"1");
		if(sysUser==null) {
			return null;
		}
		BeanUtils.copyProperties(sysUser, loginUser);
		loginUser=userMapper.getUserInfoByName(username,"1");
		return loginUser;
	}


	@Override
	public String getDatabaseType() throws SQLException {
		DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
		return getDatabaseTypeByDataSource(dataSource);
	}


	/**
	 * 获取数据库类型
	 * @param dataSource
	 * @return
	 * @throws SQLException
	 */
	private String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
		if("".equals(DB_TYPE)) {
			Connection connection = dataSource.getConnection();
			try {
				DatabaseMetaData md = connection.getMetaData();
				String dbType = md.getDatabaseProductName().toLowerCase();
				if(dbType.indexOf("mysql")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
				}else if(dbType.indexOf("oracle")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
				}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
				}else if(dbType.indexOf("postgresql")>=0) {
					DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
				}else {
					throw new BussException("数据库类型:["+dbType+"]不识别!");
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}finally {
				connection.close();
			}
		}
		return DB_TYPE;
	}
}